<?php
/**
 * Created by PhpStorm.
 * User: longli
 * Date: 2020/02/25
 * Time: 15:24
 * @link http://www.lmterp.cn
 */

namespace app\common\model;

use think\model\relation\HasMany;

/**
 * 平台账号模型
 * Class Account
 * @package app\common\model
 */
class Account extends BaseModel
{
    protected $pk = 'account_id';

    protected $autoWriteTimestamp = 'datetime';

    /**
     * 可用
     */
    const ACTIVE_Y = 1;

    /**
     * 关闭
     */
    const ACTIVE_N = 0;

    public static $ACTIVE = [
        self::ACTIVE_N => '关闭',
        self::ACTIVE_Y => '可用',
    ];

    // 设置 json 字段
    protected $json = ['token'];

    public function platform()
    {
        return $this->belongsTo(AccountPlatform::class, 'platform_id', 'platform_id');
    }

    /**
     * 检测账号或者店铺是否存在
     * @param string $name 账号或者店铺名
     * @return bool
     * @date 2020/09/15
     * @author longli
     */
    public static function hasAccount($name)
    {
        return !!static::where("username", $name)
            ->whereOr("store_name", $name)
            ->count();
    }

    /**
     * 一对多订单关联
     * @return HasMany
     * @date 2020/08/26
     * @author longli
     */
    public function orders()
    {
        return $this->hasMany(Orders::class);
    }

    /**
     * 关联账号同步配置
     * @return \think\model\relation\HasOne
     * @date 2020/09/17
     * @author longli
     */
    public function settings()
    {
        return $this->hasOne(AccountSettings::class);
    }

    public static function getAll()
    {
        return Account::where("is_active", self::ACTIVE_Y)
            ->order("sort desc,username, store_name")
            ->select();
    }

    /**
     * 模糊匹配名称
     * @param string $name 店铺名或者账号名
     * @return array|\PDOStatement|string|\think\Collection
     * @date 2020/09/15
     * @author longli
     */
    public static function getByLikeName($name)
    {
        return static::where("is_active", self::ACTIVE_Y)
            ->whereRaw("username LIKE \"%{$name}%\" OR store_name LIKE \"%{$name}%\"")
            ->select();
    }

    /**
     * 通过账号或者店铺名获取一行数据
     * @param string $name 店铺名或者账号
     * @return array|\PDOStatement|string|\think\Model|null
     * @date 2020/09/16
     * @author longli
     */
    public static function getByName($name)
    {
        return static::where("username", $name)->whereOr("store_name", $name)->find();
    }
}